package com.tbit.uqbike.webmanager.util.csv.schedule;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tbit.common.utils.SpringContextUtils;
import com.tbit.uqbike.object.pojo.DownloadHistory;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.webmanager.dao.capital.DownloadHistoryDao;
import com.tbit.uqbike.webmanager.util.csv.config.CsvExportConfig;
import com.tbit.uqbike.webmanager.util.csv.config.ExportThreadPool;
import com.tbit.uqbike.webmanager.util.csv.entity.MethodInfo;
import com.tbit.uqbike.webmanager.util.csv.util.ClassUtils;
import com.tbit.uqbike.webmanager.util.csv.util.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

/**
 * @AUTHOR: wei.xing
 * @DATE: 2022-11-19 15:34
 **/
@Slf4j
@Configuration
public class ExportScheduleTask {

    @Autowired
    ExportThreadPool pool;


    @Autowired
    DownloadHistoryDao historyDao;

    @Autowired
    CsvExportConfig config;

    /**
     * 下载定时任务
     */
    @Scheduled(cron = "0/10 * * * * ?")
    private void configureTasks() {
        //启动开关
        if (!config.getEnable()) {
            return;
        }

        //查询生成中的任务
        List<DownloadHistory> downloadList = historyDao
                .selectList(Wrappers.lambdaQuery(DownloadHistory.class)
                        .eq(DownloadHistory::getDelFlag, 0)
                        .eq(DownloadHistory::getStatus, 1)
                        .last("limit 100"));

        //没下载的数据
        if (downloadList.isEmpty()) {
            return;
        }
        //执行下载任务
        for (DownloadHistory download : downloadList) {
            log.info("========下载开始时间{}",System.currentTimeMillis());
            executeTask(download);
            log.info("========下载结束时间{}",System.currentTimeMillis());
        }

    }

    /**
     * 执行下载任务
     *
     * @param history
     */
    private void executeTask(DownloadHistory history) {
        try {
            //获取方法信息
            MethodInfo methodInfo = JacksonUtil.parseObject(history.getMethodInfo(), MethodInfo.class);
            Class targetClass = ClassUtils.loadClass(methodInfo.getClassName());
            Object targetBean = SpringContextUtils.getBean(targetClass);
            Method targetMethod = getTargetMethod(methodInfo, targetClass);
            //执行任务
            Result result = (Result) targetMethod.invoke(targetBean, methodInfo.getArgs());
            //下载成功
            updateDownloadSuccess(history.getDownloadId(), result.getData().toString());
        } catch (Exception e) {
            log.error("下载失败 " + history, e);
            updateDownloadFail(history.getDownloadId());
        }
    }

    private void updateDownloadFail(long downloadId) {
        DownloadHistory history = historyDao.selectById(downloadId);
        history.setUpdateTime(new Date());
        history.setStatus(3);
        historyDao.updateById(history);
    }

    private void updateDownloadSuccess(long downloadId, String url) {
        DownloadHistory history = historyDao.selectById(downloadId);
        history.setUpdateTime(new Date());
        history.setFileUrl(url);
        history.setStatus(2);
        historyDao.updateById(history);
    }


    /**
     * 获取目标方法
     *
     * @param methodInfo
     * @param targetClass
     * @return
     */
    private Method getTargetMethod(MethodInfo methodInfo, Class targetClass) {
        Method[] methods = targetClass.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodInfo.getMethodName())) {
                return method;
            }
        }
        throw new RuntimeException("targetMethod不存在 " + methodInfo);
    }
}
